import axios, { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from "axios"
import { ResultEnum, RedirectPageEnum } from "@/enums/httpEnum"
import { redirectErrorPage } from "@/utils/router"

const axiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_API_URL,
    timeout: ResultEnum.TIMEOUT,
})

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
    (res: AxiosResponse) => {
        const { code } = res.data as { code: number }
        if (code === null || code === undefined ||  code === ResultEnum.SUCCESS) {
            return Promise.resolve(res);
        }
        //重定向
        if(RedirectPageEnum.get(code)) redirectErrorPage(code)
        return Promise.resolve(res)
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)

export default axiosInstance